package chpt09;

import java.util.Random;
import java.util.Scanner;

class InterruptedTask implements Runnable{
	private int job = 0; // 工作数量
	
	public InterruptedTask(int job) {
		this.job = job;
	}

	@Override
	public void run() {
		Random rnd = new Random();
		Thread curThread = Thread.currentThread();
		// curThread.setPriority(Thread.MAX_PRIORITY); // 仅测试，意义不大
		while(!curThread.isInterrupted() && job >0) {
			System.out.println("Doing job "+job);
			job--;
			try {
				Thread.sleep(rnd.nextInt(1000));
			} catch (InterruptedException e) {
				System.out.println(curThread+" 被中断!");
				System.out.println("还有"+job+"项工作未完成");
				return;
			}
		}
		if(job>0)
			System.out.println("还有"+job+"项工作未完成");
		else
			System.out.println("已完成所有工作");
		}
	}

public class InterruptTest {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int job = 10;
		Thread t1 = new Thread(new InterruptedTask(job));
		t1.start();
		while(true) {
			System.out.println("是否终止线程(y/n)?");
			String choice = sc.next();
			if (choice.equalsIgnoreCase("y")){
				t1.interrupt();
				break;
			}
		}
		System.out.println("Main end");
		sc.close();
	}
}
